
#include "CxType.h"
#include "CxWriteThread.h"

using namespace ImitateTansfer;

CxWriteThread::CxWriteThread(vector<CxPort *>::reference pPort,CxWriteBuffer *pBuffer):
				m_Port(pPort),
				m_Buffer(pBuffer),
				m_spin(true)
{	
}

CxWriteThread::~CxWriteThread()
{
	Close();
}

inline	bool	CxWriteThread::Begin()
{
	return true;
}

inline	bool	CxWriteThread::Close()
{
	m_spin=false;
	m_Buffer->ClearAll();
	m_Port=NULL;
	m_Buffer->NotifyRead();
	m_thread.join();
	cout<<"Write thread have been exit....."<<endl;
	delete m_Buffer;
	return true;
}

inline	bool	CxWriteThread::Suspend()
{
	return true;
}


inline	bool	CxWriteThread::Continue()
{
	return true;
}

void	CxWriteThread::ThreadFunc()
{
    cout<<"Write thread is "<<boost::this_thread::get_id()<<endl;
	try
	{
		CX_ASSERT(m_spin);
		while(m_spin)
		{
			//ÎÞÐèµÈ´ý£¬»º³åÎÞÊý¾Ý×Ô¶¯µÈ´ý
            boost::this_thread::sleep(boost::posix_time::milliseconds(33));

			CxPackage *pack=m_Buffer->PopBuffer();

            if(m_Port==NULL  || !m_Port->IsOpen())
				delete pack;
			else 
			{
				//m_Port->WritePort(pack);
				m_Port->WritePort((BYTE*)pack->GetData(),pack->GetDataSize());
				delete pack;
			}
		}
	}
	catch(const boost::lock_error &e)
	{
        CX_ERR_MESSAGE(e.what())
	}
	catch(const boost::thread_interrupted &)
	{	
		return ;
	}
}
